// pages/idchange/idchange.js
var Bmob = require('../../dist/Bmob-1.6.0.min.js');
const {
  $Message
} = require('../../dist/base/index');
var app = getApp()
Page({
  data: {
    files: [],
    flag: false,
    majorIndex: 0,
    major: ['计算机工程与科学学院', '通信学院', '机自学院', '文学院', '法学院'],
    majorId: [],
    nickNameInput: '',
    areaIndex: 0,
    area: ['宝山校区', '嘉定校区', '延长校区'],
    multiArray: [['每天', '工作日', '周末'], ['上午', '下午', '晚上', '全天']],//二维数组，长度是多少是几列  
    multiIndex: [0, 0],
  },

  onLoad: function (options) {
    var that = this
    //从服务器上读取有多少个专业
    var majors = []
    var majorId = []
    const query = Bmob.Query("MajorList");
    query.select("name");
    query.find().then(res => {
      for (var i = 0; i < res.length; i++) {
        majors.push(
          res[i].name
        )
        majorId.push(
          res[i].objectId
        )
      }
      that.setData({
        major: majors,
        majorId: majorId
      })
    });


  },
  nickNameChange: function (e) {
    this.setData({
      nickNameInput: e.detail.value
    })
    console.log(this.data.nickNameInput)
  },

  handleClick: function () {
    //在这里上传数据！
    let that = this

    //查空
    console.log(this.data)
    return



    //检查有没有存在的数据
    var userId = app.globalData.authData.objectId
    const query = Bmob.Query("UserData");
    query.statTo("where", '{"user":{"$inQuery":{"where":{"objectId":"' + userId + '"},"className":"_User"}}}');
    query.find().then(res => {
      if (res.length) {
        console.log('查询成功，存在数据：', res[0].objectId)
        //上传数据，修改数据表
        const query = Bmob.Query("UserData");

        const pointer_user = Bmob.Pointer('_User');
        const pointer_major = Bmob.Pointer('_User');
        const poiID_user = pointer_user.set(app.globalData.authData.objectId)
        const poiID_major = pointer_major.set(that.data.majorId[that.data.majorIndex])
        console.log('准备传输数据给objectid：', app.globalData.authData.objectId)
        //上传图片
        // console.log('itemn', that.data.files[0], app.globalData.userInfo.nickName)
        if (that.data.files.length) {
          var file = Bmob.File(app.globalData.userInfo.nickName + '.jpg', that.data.files[0]);
          file.save().then(res1 => {
            console.log('文件上传成功：', JSON.parse(res1[0]));
            console.log('文件上传成功 大小：', res1.length);
            query.get(res[0].objectId).then(res => {
              res.remove('time', [0, 1, 2, 3])
              res.save()
              res.set('user', poiID_user);
              res.set('major', poiID_major);
              res.set('area', parseInt(that.data.areaIndex));
              res.set('nickName', that.data.nickNameInput);
              res.add("time", that.data.multiIndex);
              res.set("userPic", JSON.parse(res1[0]));
              var gender;
              if (app.globalData.userInfo.gender==2)
                {gender=false}
              else{gender=true}
              res.set("gender", gender)
              res.save()
              $Message({
                content: '上传成功',
                type: 'success'
              });
            })
          }).catch(err => {
            $Message({
              content: '查询失败！',
              type: 'error'
            });
            console.log(err)
          })
        }
        else{
          query.get(res[0].objectId).then(res => {
            res.remove('time', [0, 1, 2, 3])
            res.save()
            res.set('user', poiID_user);
            res.set('major', poiID_major);
            res.set('area', parseInt(that.data.areaIndex));
            res.set('nickName', that.data.nickNameInput);
            res.add("time", that.data.multiIndex);
            res.set("gender", Boolean(app.globalData.userInfo.gender))
            res.save()
            console.log(res)
          })

        }

      }
      else {
        console.log('查询成功，不存在数据：', res)

        //上传数据，新建数据表
        const query = Bmob.Query("UserData");

        const pointer_user = Bmob.Pointer('_User');
        const pointer_major = Bmob.Pointer('_User');
        const poiID_user = pointer_user.set(app.globalData.authData.objectId)
        const poiID_major = pointer_major.set(that.data.majorId[that.data.majorIndex])
        console.log('准备传输数据给objectid：', app.globalData.authData.objectId)

        query.set('user', poiID_user);
        query.set('major', poiID_major);
        query.set('area', that.data.areaIndex);
        query.add("time", that.data.multiIndex);

        query.save().then(res => {
          $Message({
            content: '上传成功！',
            type: 'success'
          });
          console.log(res)
        }).catch(err => {
          $Message({
            content: '上传失败！',
            type: 'error'
          });
          console.log(err)
        })
      }
    }).catch(err => {
      $Message({
        content: '上传数据失败！',
        type: 'error'
      });
      console.log(err)
    })





  },//提交按钮相应的函数
  chooseImage: function (e) {
    var that = this;
    wx.chooseImage({
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        that.setData({
          files: that.data.files.concat(res.tempFilePaths),
          flag: true
        });
      }
    })
  },
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },
  bindPickerChange: function (e) {
    this.setData({
      majorIndex: e.detail.value
    })
  },
  areabindPickerChange: function (e) {

    console.log('area发送选择改变，携带值为', e.detail.value)
    this.setData({
      areaIndex: e.detail.value
    })
  },
  bindMultiPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      multiIndex: e.detail.value
    })
    console.log(this.data.mutlIndex)
  },
  // handleFruitChange({ detail = {} }) {
  //   const index = this.data.current.indexOf(detail.value);
  //   index === -1 ? this.data.current.push(detail.value) : this.data.current.splice(index, 1);
  //   this.setData({
  //     current: this.data.current
  //   });
  // },
  // handleClick() {
  //   this.setData({
  //     position: this.data.position.indexOf('left') !== -1 ? 'right' : 'left',
  //   });
  // },
  // handleDisabled() {
  //   this.setData({
  //     disabled: !this.data.disabled
  //   });
  // },
  // handleAnimalChange({ detail = {} }) {
  //   this.setData({
  //     checked: detail.current
  //   });
  // },





  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
})